package cn.wyl.pet.service.impl;

import cn.wyl.basic.exception.BusinessException;
import cn.wyl.basic.service.IBaiduAiAuditService;
import cn.wyl.basic.util.*;
import cn.wyl.order.domain.OrderPetAcquisition;
import cn.wyl.order.dto.OrderDto;
import cn.wyl.order.mapper.OrderPetAcquisitionMapper;
import cn.wyl.org.domain.Employee;
import cn.wyl.org.domain.Shop;
import cn.wyl.org.mapper.EmployeeMapper;
import cn.wyl.org.mapper.ShopMapper;
import cn.wyl.pet.domain.SearchMasterMsg;
import cn.wyl.pet.domain.SearchMasterMsgAuditLog;
import cn.wyl.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.wyl.pet.mapper.SearchMasterMsgMapper;
import cn.wyl.pet.query.SearchMasterMsgQuery;
import cn.wyl.pet.service.ISearchMasterMsgService;
import cn.wyl.basic.service.impl.BaseServiceImpl;
import cn.wyl.user.domain.Logininfo;
import cn.wyl.user.domain.User;
import cn.wyl.user.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 业务实现类：
 */
@Service
@Transactional
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private IBaiduAiAuditService baiduAiAuditService;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        // name: '小七',
        // price: 10,
        // age: 3,
        // gender: 1,
        // coatColor: '黑色',
        // resources: null,
        // petType: 1,
        // address: null,
        // title: '小七寻主'
        // UserId -发布人 - request获取
        // shopId - 分配给哪一个店铺，审核通过之后再分配 - 现在不用管
        // note - 发布寻主消息的说明 - 不用管

        //一、保存到数据库：如果审核失败
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        searchMasterMsg.setUserId(user.getId());
        searchMasterMsgMapper.save(searchMasterMsg);//有自增id

        //二、智能审核
        Boolean bool1 = baiduAiAuditService.textAudit(searchMasterMsg.getName() + searchMasterMsg.getTitle());
        Boolean bool2 = baiduAiAuditService.imageAudit(searchMasterMsg.getResources());
        if (bool1 && bool2) {
            //三：审核通过：
            // 1.改state=1
            searchMasterMsg.setState(1);
            // 2.分配最近50公里以内的店铺
            List<Shop> shops = shopMapper.findAll();
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            Shop nearestShop = DistanceUtils.getNearestShop(point, shops);
            if (nearestShop == null) {
                searchMasterMsg.setState(3);
            } else {
                searchMasterMsg.setShopId(nearestShop.getId());
                // 5.发短信或邮箱告诉店铺管理员去接回宠物
                Employee employee = employeeMapper.findById(nearestShop.getAdminId());
                //SmsUtils.sendSms(employee.getPhone(),"你有新的宠物订单，请在3天之内去【"+searchMasterMsg.getAddress()+"】接回宠物");
                System.out.println("你有新的宠物订单，请在3天之内去【" + searchMasterMsg.getAddress() + "】接回宠物");
            }
            // 3.保存到数据库
            searchMasterMsgMapper.update(searchMasterMsg);

            // 4.记录审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(1);
            //无审核人
            log.setNote("审核成功");
            searchMasterMsgAuditLogMapper.save(log);

            return new AjaxResult();
        } else {
            //四：审核失败:
            // 1.改状态state=-1
            searchMasterMsg.setState(-1);
            searchMasterMsgMapper.update(searchMasterMsg);

            // 2.记录审核日志
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setState(0);
            //无审核人
            log.setNote("审核失败");
            searchMasterMsgAuditLogMapper.save(log);

            // 3.发短信或邮箱告诉用户重新修改资料再分布
            //SmsUtils.sendSms(user.getPhone(),"你的宠物寻主请求审核失败，请重新修改之后再发布");
            System.out.println("你的宠物寻主请求审核失败，请重新修改之后再发布");
            return AjaxResult.me().setSuccess(false).setMsg("寻主消息审核失败");
        }
    }

    @Override
    public PageList<SearchMasterMsg> user(SearchMasterMsgQuery query, HttpServletRequest request) {
        //获取用户id
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.findByLogininfoId(logininfo.getId());
        query.setUserId(user.getId());

        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHande(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(1);//待处理寻主信息

        //区分平台管理员和店铺管理员
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.findByLogininfoId(logininfo.getId());
        if (employee.getShop_id() != null) {//店铺管理员
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    //店铺管理员不能查询已经完成的寻主信息，通过菜单权限限制
    @Override
    public PageList<SearchMasterMsg> finish(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(2);//已完成
        return super.queryPage(query);
    }

    //所有管理员都可以查看寻主池的信息
    @Override
    public PageList<SearchMasterMsg> toSearchMasterPool(SearchMasterMsgQuery query, HttpServletRequest request) {
        query.setState(3);//寻主池

        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        searchMasterMsgMapper.reject(id);
    }

    @Override
    public void accept(OrderDto orderDto) {
        //一：判断当前订单是否正在处理
        OrderPetAcquisition dbOrder = orderPetAcquisitionMapper.findByMsgId(orderDto.getMsgId());
        if (dbOrder != null && dbOrder.getState() == 0) {
            throw new BusinessException("订单正在处理，请勿重复处理");
        }
        //二：生成收购订单
        SearchMasterMsg msg = searchMasterMsgMapper.findById(orderDto.getMsgId());
        OrderPetAcquisition order = orderDto2Order(orderDto, msg);
        orderPetAcquisitionMapper.save(order);

        //三：通知接单人
        //Employee employee = employeeMapper.findById(orderDto.getHandler());
        //SmsUtils.sendSms(employee.getPhone(),"你有新的订单，请在3天内去"+order.getAddress()+"接回宠物");
        System.out.println("你有新的宠物收购订单，请在3天内去" + order.getAddress() + "接回宠物");

    }

    private OrderPetAcquisition orderDto2Order(OrderDto orderDto, SearchMasterMsg msg) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(msg.getUserId());
        order.setOrderSn(orderSn);
        order.setDigest(orderDto.getNote());
        //3天之内没有接单就自动取消 - 定时器
        order.setLastcomfirmtime(new Date((System.currentTimeMillis() + 3*24*3600*1000)));
        order.setPrice(msg.getPrice());
        //支付类型 - 确认订单时设置
        //宠物id - 确认订单并接回宠物时设置
        order.setUserId(msg.getUserId());
        order.setShopId(msg.getShopId());
        order.setAddress(msg.getAddress());
        order.setEmpId(orderDto.getHandler());
        order.setSearchMasterMsgId(orderDto.getMsgId());

        return order;
    }
}
